import router from '@/router/index'
//理由加载进度条组件
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
//引入user小仓库
import useUserStore from './store/modules/user'
//引入pinia大仓库
import pinia from './store/index'

//路由加载进度条右侧加载小球样式关闭
nprogress.configure({ showSpinner: false })
console.log(5555)
let userStore = useUserStore(pinia)
console.log(userStore.token)

//路由前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  let token = userStore.token
  let status
  try {
    let username = userStore.userInfos.username
    if (username) {
      status = true
    } else {
      status = false
    }
  } catch (error) {}

  nprogress.start()
  if (token) {
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (status) {
        next()
      } else {
        try {
          await userStore.getUserInfo()
          next()
        } catch (error) {
          await userStore.userLogOut()
          next({ path: '/login' })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login' })
    }
  }
})
router.afterEach((to: any, from: any) => {
  nprogress.done()
})
